#include <arch/io.h>
#include <hal/rtc.h>
#include <type.h>
#include <clock.h>

#define LOG_TAG "RTC"
#include <log.h>

u8 bcd2dec(u8 bcd) {
    return (bcd >> 4) * 10 + (bcd & 0xF);
}

void rtc_write(u8 reg, u8 val) {
    outb(0x70, (1 << 7) | reg); // 禁用 NMI
    outb(0x71, val);
}

u8 rtc_read(u8 reg) {
    outb(0x70, (1 << 7) | reg); // 禁用 NMI
    return inb(0x71);
}

rtc_time_t read_rtc_time() {
    rtc_time_t t;

    while (rtc_read(0x0A) & 0x80);

    t.second = rtc_read(0x00);
    t.minute = rtc_read(0x02);
    t.hour = rtc_read(0x04);
    t.day = rtc_read(0x07);
    t.month = rtc_read(0x08);
    t.year = rtc_read(0x09);

    t.second = bcd2dec(t.second);
    t.minute = bcd2dec(t.minute);
    t.hour = bcd2dec(t.hour);
    t.day = bcd2dec(t.day);
    t.month = bcd2dec(t.month);
    t.year = bcd2dec(t.year);

    t.year += RTC_CURRENT_CENTRY * 100;
    return t;
}

void show_rtc_time() {
    rtc_time_t t = read_rtc_time();
    LOGW("RTC: %d-%d-%d %d:%d:%d\n", t.year, t.month, t.day, t.hour, t.minute, t.second);
}